package com.example.teamwork.impl;

import com.example.teamwork.mapper.OrderMapper;
import com.example.teamwork.pojo.Order;
import com.example.teamwork.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 〈邮件管理〉<br>
 * 〈〉
 * @author  SongPeng
 * @date  2021/11/21 14:24
 * @version 1.0
 */

@Service
public class MailServiceImpl implements MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private OrderMapper orderMapper;

    private static final String SENDER = "1239874028@qq.com";

    /**
     * 发送普通邮件
     * @param orderId      预约id
     */
    @Override
    public void sendSimpleMailMessge(Long orderId) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SENDER);
        Order order=orderMapper.selectByPrimaryKey(orderId);
        String to=order.getOrderEmail();
        String subject="预约审核结果";
        String content="您的预约申请已经通过,请按时来访";
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        order.setOrderStatus(1);
        orderMapper.updateByPrimaryKeySelective(order);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }
    }

    /**
     * 发送 HTML 邮件
     *
     * @param orderId      预约 id
     */
    @Override
    public void sendMimeMessge(Long orderId) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            Order order=orderMapper.selectByPrimaryKey(orderId);
            order.setOrderStatus(1);
            orderMapper.updateByPrimaryKeySelective(order);
            String to=order.getOrderEmail();
            String content = "<h1>抱歉，您的预约申请被拒绝了！</h1>";
            helper.setTo(to);
            String subject="预约审核结果";
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("发送MimeMessge时发生异常！", e);
        }
    }

}
